<template>
  <!-- 用户标签-编辑 -->
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="60%"
    class="el-dialog-box component-user-label-edit"
    @close="onCloseClr()"
  >
    <div class="edit-label-content">
      <div class="label-name-line currency-line">
        <div class="title">
          <span class="must-term">*</span>{{ $t('user.labelName') }}
        </div>
        <div>
          <el-input
            v-model="labelName"
            type="text"
            maxlength="10"
            show-word-limit
            @blur="labelName = handleInputSpaces(labelName)"
          />
        </div>
      </div>
      <div class="label-type-line currency-line">
        <div class="title">
          <span class="must-term">*</span>{{ $t('user.labelType') }}
        </div>
        <el-radio
          v-model="labelType"
          label="1"
          :disabled="isDisaCondiLabel"
        >
          {{ $t('user.conditionLabel') }}
        </el-radio>
        <el-radio
          v-model="labelType"
          label="0"
          :disabled="isDisaCustLabel"
        >
          {{ $t('user.manualLabel') }}
        </el-radio>
      </div>
      <div v-if="labelType==1">
        <div class="label-condition-title-line">
          {{ $t('user.conditionSetting') }}<span class="tips">{{ $t('user.conditionSettingTips') }}</span>
        </div>
        <div class="transaction-condition-line currency-line">
          <div class="title">
            {{ $t('user.tradingConditions') }}
          </div>
          <div class="deal-condition-content module-content">
            <div class="option-line">
              <el-checkbox v-model="isNearConTime">
                {{ $t('user.nearConsuTime') }}
              </el-checkbox>
              <el-select
                v-model="nearConTimeValue"
                :disabled="!isNearConTime"
                :placeholder="$t('user.pleaseSelect')"
              >
                <el-option
                  v-for="item in nearConTimeOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="option-line">
              <el-checkbox v-model="isConNum">
                {{ $t('user.consuNum') }}
              </el-checkbox>
              <el-select
                v-model="conNumValue"
                :disabled="!isConNum"
                :placeholder="$t('user.pleaseSelect')"
              >
                <el-option
                  v-for="item in conNumOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div class="unit-wrapper first-iterm">
                <el-input
                  v-model.number="conNumBegInp"
                  min="0"
                  :disabled="!isConNum"
                  class="cur-inp"
                  @blur="checkNumber (1)"
                >
                  <template #append>
                    {{ $t('user.bout') }}
                  </template>
                </el-input>
              </div>
              <span class="interval-line">-</span>
              <div class="unit-wrapper">
                <el-input
                  v-model.number="conNumEndInp"
                  min="0"
                  :disabled="!isConNum"
                  class="cur-inp"
                  @blur="checkNumber (2)"
                >
                  <template #append>
                    {{ $t('user.bout') }}
                  </template>
                </el-input>
              </div>
            </div>
            <div class="option-line">
              <el-checkbox v-model="isConAmount">
                {{ $t('user.consuAmount') }}
              </el-checkbox>
              <el-select
                v-model="conAmountValue"
                :disabled="!isConAmount"
                :placeholder="$t('user.pleaseSelect')"
              >
                <el-option
                  v-for="item in conAmountOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div class="unit-wrapper first-iterm">
                <el-input
                  v-model.number="conAmountBegInp"
                  min="0"
                  :disabled="!isConAmount"
                  class="cur-inp"
                  @blur="checkNumber (3)"
                >
                  <template #append>
                    {{ $t('user.yuan') }}
                  </template>
                </el-input>
              </div>
              <span class="interval-line">-</span>
              <div class="unit-wrapper">
                <el-input
                  v-model.number="conAmountEndInp"
                  min="0"
                  :disabled="!isConAmount"
                  class="cur-inp"
                  @blur="checkNumber (4)"
                >
                  <template #append>
                    {{ $t('user.yuan') }}
                  </template>
                </el-input>
              </div>
            </div>
            <div class="option-line">
              <el-checkbox v-model="isOrderAverPrice">
                {{ $t('user.averPri') }}
              </el-checkbox>
              <el-select
                v-model="orderAverPriceValue"
                :disabled="!isOrderAverPrice"
                :placeholder="$t('user.pleaseSelect')"
              >
                <el-option
                  v-for="item in orderAverPriceOpts"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <div class="unit-wrapper first-iterm">
                <el-input
                  v-model.number="orderAverPriceBegInp"
                  min="0"
                  :disabled="!isOrderAverPrice"
                  class="cur-inp"
                  @blur="checkNumber (5)"
                >
                  <template #append>
                    {{ $t('user.yuan') }}
                  </template>
                </el-input>
              </div>
              <span class="interval-line">-</span>
              <div class="unit-wrapper">
                <el-input
                  v-model.number="orderAverPriceEndInp"
                  min="0"
                  :disabled="!isOrderAverPrice"
                  class="cur-inp"
                  @blur="checkNumber (6)"
                >
                  <template #append>
                    {{ $t('user.yuan') }}
                  </template>
                </el-input>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 按键 -->
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="dialogVisible = false"
        >
          {{ $t('user.calcel') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="preserveLabel"
        >
          {{ $t('user.preservation') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import moment from 'moment'
import { ElMessage } from 'element-plus'

const props = defineProps({
  tagCategory: {
    default: 0,
    type: Number
  }
})
const emit = defineEmits(['refreshLabelList'])

// 交易条件
const dealConditionOpts = [{
  value: 1,
  label: $t('user.today')
}, {
  value: 2,
  label: $t('user.lastSevenDay')
}, {
  value: 3,
  label: $t('user.lastFifteenDay')
}, {
  value: 4,
  label: $t('user.lastThirtyDay')
}, {
  value: 5,
  label: $t('user.lastFortyFiveDay')
}, {
  value: 6,
  label: $t('user.lastSixtyDay')
}, {
  value: 7,
  label: $t('user.lastNinetyDay')
}, {
  value: 8,
  label: $t('user.lastOneHundredEightyDay')
}, {
  value: 0,
  label: $t('user.unlimited')
}]

// 充值次数

let beCustTimeValue = 0
watch(() => beCustTimeValue, () => {
  changeTimeRan(0)
})

let followTimeValue = 0
watch(() => followTimeValue, () => {
  changeTimeRan(1)
})

onMounted(() => {
  initPullSelOpts()
  changeTimeRan(0)
  changeTimeRan(1)
  changeTimeRan(2)
})

let userTagId = null
const dialogVisible = ref(false)
const isDisaCustLabel = ref(false)
const isDisaCondiLabel = ref(false)
const labelType = ref('1')
const title = ref($t('user.addLabel'))
// 弹出弹框
const init = (userTagIdPar, tagType) => {
  dialogVisible.value = true
  userTagId = userTagIdPar
  if (tagType === 0) {
    isDisaCondiLabel.value = true
    labelType.value = '0'
    if (userTagId !== '') {
      title.value = $t('user.editLabel')
      getEditLabelDetail()
    }
  } else if (tagType === 1) {
    isDisaCustLabel.value = true
    labelType.value = '1'
    if (userTagId !== '') {
      title.value = $t('user.editLabel')
      getEditLabelDetail()
    }
  }
}

/**
 * 输入框纯空格处理
 */
const handleInputSpaces = (value) => {
  if (!value) {
    return ''
  }
  if (!value.trim()) {
    return value.trim()
  } else {
    return value
  }
}

const conNumBegInp = ref('')
const conNumEndInp = ref('')
const conAmountBegInp = ref('')
const conAmountEndInp = ref('')
const orderAverPriceBegInp = ref('')
const orderAverPriceEndInp = ref('')
let recharNumBegInp = ''
let recharNumEndInp = ''
/**
 * 输入框的数据改变时，对值进行校验
 */
const checkNumber = (type) => {
  // 消费次数
  if (type === 1) {
    let BegNum = Math.round(parseInt(conNumBegInp.value))
    if (!BegNum) {
      BegNum = 0
    } else if (BegNum < 0) {
      BegNum = 0
    } else if (BegNum > 100000) {
      BegNum = 100000
    }
    conNumBegInp.value = BegNum
  }
  if (type === 2) {
    let endNum = Math.round(parseInt(conNumEndInp.value))
    if (!endNum) {
      endNum = 0
    } else if (endNum < 0) {
      endNum = 0
    } else if (endNum > 100000) {
      endNum = 100000
    }
    conNumEndInp.value = endNum
  }
  // 消费金额
  if (type === 3) {
    let conBegAmountNum = Math.round(parseFloat(conAmountBegInp.value).toFixed(2))
    if (!conBegAmountNum) {
      conBegAmountNum = 0
    } else if (conBegAmountNum < 0) {
      conBegAmountNum = 0
    } else if (conBegAmountNum >= 100000000) {
      conBegAmountNum = 100000000
    }
    conAmountBegInp.value = conBegAmountNum
  }
  if (type === 4) {
    let conEndAmountNum = Math.round(parseFloat(conAmountEndInp.value).toFixed(2))
    if (!conEndAmountNum) {
      conEndAmountNum = 0
    } else if (conEndAmountNum < 0) {
      conEndAmountNum = 0
    } else if (conEndAmountNum >= 100000000) {
      conEndAmountNum = 100000000
    }
    conAmountEndInp.value = conEndAmountNum
  }
  // 订单均价
  if (type === 5) {
    let ordAverPriceBegNum = Math.round(parseFloat(orderAverPriceBegInp.value).toFixed(2))
    if (!ordAverPriceBegNum) {
      ordAverPriceBegNum = 0
    } else if (ordAverPriceBegNum < 0) {
      ordAverPriceBegNum = 0
    } else if (ordAverPriceBegNum >= 100000000) {
      ordAverPriceBegNum = 100000000
    }
    orderAverPriceBegInp.value = ordAverPriceBegNum
  }
  if (type === 6) {
    let ordAverPriceEndNum = Math.round(parseFloat(orderAverPriceEndInp.value).toFixed(2))
    if (!ordAverPriceEndNum) {
      ordAverPriceEndNum = 0
    } else if (ordAverPriceEndNum < 0) {
      ordAverPriceEndNum = 0
    } else if (ordAverPriceEndNum >= 100000000) {
      ordAverPriceEndNum = 100000000
    }
    orderAverPriceEndInp.value = ordAverPriceEndNum
  }
  // 充值次数
  if (type === 9) {
    let recharBegNum = Math.round(parseInt(recharNumBegInp))
    if (!recharBegNum) {
      recharBegNum = 0
    } else if (recharBegNum < 0) {
      recharBegNum = 0
    } else if (recharBegNum > 100000) {
      recharBegNum = 100000
    }
    recharNumBegInp = recharBegNum
  }
  if (type === 10) {
    let recharEndNum = Math.round(parseInt(recharNumEndInp))
    if (!recharEndNum) {
      recharEndNum = 0
    } else if (recharEndNum < 0) {
      recharEndNum = 0
    } else if (recharEndNum > 100000) {
      recharEndNum = 100000
    }
    recharNumEndInp = recharEndNum
  }
}

// 最近消费时间
const nearConTimeOpts = ref([])
// 消费次数
const conNumOpts = ref([])
// 消费金额
const conAmountOpts = ref([])
// 订单均价
const orderAverPriceOpts = ref([])
const initPullSelOpts = () => {
  // 交易条件
  nearConTimeOpts.value = dealConditionOpts
  conNumOpts.value = dealConditionOpts
  conAmountOpts.value = dealConditionOpts
  orderAverPriceOpts.value = dealConditionOpts
}

const labelName = ref('')
let isfollowTimeChecked = false
let followTimeRange = []
const isNearConTime = ref(false)
const nearConTimeValue = ref(1)
const isConNum = ref(false)
const conNumValue = ref(1)
const isConAmount = ref(false)
const conAmountValue = ref(1)
const isOrderAverPrice = ref(false)
const orderAverPriceValue = ref(1)
let isRecharNum = false
let recharNumValue = 1
// 获取单个标签的详情
const getEditLabelDetail = () => {
  http({
    url: http.adornUrl('/user/userTag/info/' + userTagId),
    method: 'GET',
    data: http.adornData({})
  }).then(({ data }) => {
    if (labelType.value === '0') {
      labelName.value = data.tagName
    } else if (labelType.value === '1') {
      labelName.value = data.tagName
      // 成为客户时间
      if (data.registerMinTime !== null && data.registerMaxTime !== null) {
        beCustTimeValue = 6
      }
      // 关注时间
      if (data.subscribeMinTime !== null && data.subscribeMaxTime !== null) {
        const followTimeRangePar = []
        isfollowTimeChecked = true
        followTimeValue = 6
        followTimeRangePar.push(data.subscribeMinTime)
        followTimeRangePar.push(data.subscribeMaxTime)
        followTimeRange = followTimeRangePar
      }
      // 最近消费时间
      if (data.recentPurchaseTime !== null) {
        isNearConTime.value = true
        nearConTimeValue.value = data.recentPurchaseTime
      }
      // 消费次数
      if (data.purchaseNumTime !== null && data.purchaseNumMinNum !== null && data.purchaseNumMaxNum !== null) {
        isConNum.value = true
        conNumValue.value = data.purchaseNumTime
        conNumBegInp.value = data.purchaseNumMinNum
        conNumEndInp.value = data.purchaseNumMaxNum
      }
      // 消费金额
      if (data.purchaseAmountTime !== null && data.purchaseAmountMinAmount !== null && data.purchaseAmountMaxAmount !== null) {
        isConAmount.value = true
        conAmountValue.value = data.purchaseAmountTime
        conAmountBegInp.value = data.purchaseAmountMinAmount
        conAmountEndInp.value = data.purchaseAmountMaxAmount
      }
      // 订单均价
      if (data.orderAveragePriceTime !== null && data.orderAveragePriceMinAmount !== null && data.orderAveragePriceMaxAmount !== null) {
        isOrderAverPrice.value = true
        orderAverPriceValue.value = data.orderAveragePriceTime
        orderAverPriceBegInp.value = data.orderAveragePriceMinAmount
        orderAverPriceEndInp.value = data.orderAveragePriceMaxAmount
      }

      // 充值次数
      if (data.rechargeNumTime !== null && data.rechargeNumMinNum !== null && data.rechargeNumMaxNum !== null) {
        isRecharNum = true
        recharNumValue = data.rechargeNumTime
        recharNumBegInp = data.rechargeNumMinNum
        recharNumEndInp = data.rechargeNumMaxNum
      }
    }
  })
}

// 改变时间范围
const changeTimeRan = (value) => {
  // value: 0-成为客户时间 1-关注时间 2-成为会员时间
  let seleItem = null
  const timeRange = []
  const time = new Date()
  let beginTime = ''
  let endTime = ''
  if (value === 0) {
    seleItem = beCustTimeValue
  } else if (value === 1) {
    seleItem = followTimeValue
  }

  if (seleItem === 0) {
    beginTime = moment(time).format('LL')
    endTime = beginTime
  } else if (seleItem === 1) {
    beginTime = moment(time).add(-1, 'days').format('L')
    endTime = beginTime
  } else if (seleItem === 2) {
    beginTime = moment(time).add(-7, 'days').format('L')
    endTime = moment(time).add(-1, 'days').format('L')
  } else if (seleItem === 3) {
    beginTime = moment(time).add(-30, 'days').format('L')
    endTime = moment(time).add(-1, 'days').format('L')
  } else if (seleItem === 4) {
    // 本月的开始结束时间
    beginTime = moment(time).startOf('month').format('L')
    endTime = moment(time).endOf('month').format('L')
  } else if (seleItem === 5) {
    // 上个月的开始结束时间
    beginTime = moment(time).add(-1, 'month').startOf('month').format('L')
    endTime = moment(time).add(-1, 'month').endOf('month').format('L')
  }
  if (seleItem !== 6) {
    timeRange.push(beginTime)
    timeRange.push(endTime)
    if (value === 1) {
      followTimeRange = timeRange
    }
  }
}

// 增加/编辑标签
// eslint-disable-next-line max-lines-per-function
const preserveLabel = () => {
  // 判断是否为整数/零的正则
  const posIntReg = /^([0]|[1-9][0-9]*)$/
  const tagType = labelType.value
  const tagName = labelName.value
  let addOrEditMeth = ''
  // 新增标签
  if (tagType === '0') {
    // 手动标签
    if (!tagName) {
      ElMessage.warning($t('user.labelNameNullTips'))
      return
    }
    // 判断是新增/编辑
    if (userTagId !== '') {
      addOrEditMeth = 'PUT'
    } else {
      addOrEditMeth = 'POST'
    }
    const params = {
      userTagId,
      tagType,
      tagName,
      tagCategory: props.tagCategory
    }
    http({
      url: http.adornUrl('/user/userTag'),
      method: addOrEditMeth,
      data: http.adornData(params)
    }).then(() => {
      dialogVisible.value = false
      ElMessage({
        message: $t('user.success'),
        type: 'success',
        duration: 1500
      })
      emit('refreshLabelList', true)
    })
  } else if (tagType === '1') {
    // 清空条件的参数标记
    const clearRegisterTime = false
    let clearSubscribeTime = false
    const clearToBeMemberTime = false
    let clearRecentPurchaseTime = false
    let clearPurchaseNum = false
    let clearPurchaseAmount = false
    let clearOrderAveragePrice = false
    const clearRechargeAmount = false
    let clearRechargeNum = false
    // 判断是新增/编辑
    if (userTagId !== '') {
      addOrEditMeth = 'PUT'
    } else {
      addOrEditMeth = 'POST'
    }
    // 判断是否选中某个条件，选中就就不能为空
    // 成为客户时间
    const registerMinTime = ''
    const registerMaxTime = ''
    // 关注时间
    let subscribeMinTime = ''
    let subscribeMaxTime = ''
    if (isfollowTimeChecked === true && followTimeRange !== null && followTimeRange[0] !== '' && followTimeRange[1] !== '') {
      subscribeMinTime = moment(followTimeRange[0]).startOf('days').format('LL')
      subscribeMaxTime = moment(followTimeRange[1]).endOf('days').format('LL')
    }
    if (isfollowTimeChecked === false) {
      clearSubscribeTime = true
    }
    // 最近消费时间
    let recentPurchaseTime = ''
    if (isNearConTime.value === true) {
      recentPurchaseTime = nearConTimeValue.value
    } else {
      clearRecentPurchaseTime = true
    }
    // 消费次数
    let purchaseNumTime = ''
    let purchaseNumMinNum = ''
    let purchaseNumMaxNum = ''
    if (isConNum.value === true) {
      purchaseNumTime = conNumValue.value
      if (posIntReg.test(conNumBegInp.value) && posIntReg.test(conNumEndInp.value)) {
        purchaseNumMinNum = conNumBegInp.value
        purchaseNumMaxNum = conNumEndInp.value
      }
    } else {
      clearPurchaseNum = true
    }
    // 消费金额
    let purchaseAmountTime = ''
    let purchaseAmountMinAmount = ''
    let purchaseAmountMaxAmount = ''
    if (isConAmount.value === true) {
      purchaseAmountTime = conAmountValue.value
      if (posIntReg.test(conAmountBegInp.value) && posIntReg.test(conAmountEndInp.value)) {
        purchaseAmountMinAmount = conAmountBegInp.value
        purchaseAmountMaxAmount = conAmountEndInp.value
      }
    } else {
      clearPurchaseAmount = true
    }
    // 订单均价
    let orderAveragePriceTime = ''
    let orderAveragePriceMinAmount = ''
    let orderAveragePriceMaxAmount = ''
    if (isOrderAverPrice.value === true) {
      orderAveragePriceTime = orderAverPriceValue.value
      if (posIntReg.test(orderAverPriceBegInp.value) && posIntReg.test(orderAverPriceEndInp.value)) {
        orderAveragePriceMinAmount = orderAverPriceBegInp.value
        orderAveragePriceMaxAmount = orderAverPriceEndInp.value
      }
    } else {
      clearOrderAveragePrice = true
    }
    // 充值金额
    const rechargeAmountTime = ''
    const rechargeAmountMinAmount = ''
    const rechargeAmountMaxAmount = ''
    // 充值次数
    let rechargeNumTime = ''
    let rechargeNumMinNum = ''
    let rechargeNumMaxNum = ''
    if (isRecharNum === true) {
      rechargeNumTime = recharNumValue
      if (posIntReg.test(recharNumBegInp) && posIntReg.test(recharNumEndInp)) {
        rechargeNumMinNum = recharNumBegInp
        rechargeNumMaxNum = recharNumEndInp
      }
    } else {
      clearRechargeNum = true
    }
    if (tagName.trim() === '') {
      ElMessage.warning($t('user.labelNameNullTips'))
    } else if (
      isConNum.value === false && isConAmount.value === false && isOrderAverPrice.value === false &&
      isRecharNum === false && isNearConTime.value === false) {
      ElMessage.warning($t('user.requireOne'))
    } else if (isfollowTimeChecked === true && (followTimeRange === null || followTimeRange[0] === '' || followTimeRange[1] === '')) {
      ElMessage.warning($t('user.followTimeNullTips'))
    } else if (isConNum.value === true && (purchaseNumMinNum === '' || purchaseNumMaxNum === '')) {
      ElMessage.warning($t('user.consuNumNullTips'))
    } else if (isConAmount.value === true && (purchaseAmountMinAmount === '' || purchaseAmountMaxAmount === '')) {
      ElMessage.warning($t('user.consuAmountNullTips'))
    } else if (isOrderAverPrice.value === true && (orderAveragePriceMinAmount === '' || orderAveragePriceMaxAmount === '')) {
      ElMessage.warning($t('user.averPriNullTips'))
    } else if (isRecharNum === true && (rechargeNumMinNum === '' || rechargeNumMaxNum === '')) {
      ElMessage.warning($t('user.rechargeNumberNullTips'))
    } else {
      const params = {
        userTagId,
        tagType,
        tagName,
        registerMinTime,
        registerMaxTime,
        subscribeMinTime,
        subscribeMaxTime,
        recentPurchaseTime,
        purchaseNumTime,
        purchaseNumMinNum,
        purchaseNumMaxNum,
        purchaseAmountTime,
        purchaseAmountMinAmount,
        purchaseAmountMaxAmount,
        orderAveragePriceTime,
        orderAveragePriceMinAmount,
        orderAveragePriceMaxAmount,
        rechargeAmountTime,
        rechargeAmountMinAmount,
        rechargeAmountMaxAmount,
        rechargeNumTime,
        rechargeNumMinNum,
        rechargeNumMaxNum,
        clearRegisterTime,
        clearSubscribeTime,
        clearToBeMemberTime,
        clearRecentPurchaseTime,
        clearPurchaseNum,
        clearPurchaseAmount,
        clearOrderAveragePrice,
        clearRechargeAmount,
        clearRechargeNum,
        tagCategory: props.tagCategory
      }
      http({
        url: http.adornUrl('/user/userTag'),
        method: addOrEditMeth,
        data: http.adornData(params)
      }).then(() => {
        dialogVisible.value = false
        ElMessage({
          message: $t('user.success'),
          type: 'success',
          duration: 1500
        })
        emit('refreshLabelList', true)
      })
    }
  }
}

const onCloseClr = () => {
  emit('refreshLabelList', false)
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
@use "index";
</style>
